﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Text.RegularExpressions;

namespace Expressionista.Dialogs
{
	/// <summary>
	/// Interaction logic for ImportDialog.xaml
	/// </summary>
	public partial class ImportDialog : Window
	{
		private Regex importedRegex;

		public string ImportedString
		{
			get
			{
				return convertCSToRegexStr(ImportTB.Text);
			}
		}

		public Regex ImportedRegex
		{
			get
			{
				return importedRegex;
			}
		}


		public ImportDialog()
		{
			InitializeComponent();
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			if (!(ImportTB.Text.StartsWith("@") || ImportTB.Text.StartsWith("\"")))
			{
				MessageBox.Show("Error.  String must begin with '@' or '\"'", "Error");
				return;
			}

			Button b = sender as Button;

			if (b.Content.ToString() == "Import")
			{
				DialogResult = true;
			}
			else
			{
				DialogResult = false;
			}
		}

		private bool buildRegex()
		{
			string regexStr = convertCSToRegexStr(ImportTB.Text);
			try
			{
				importedRegex = new Regex(regexStr);
				return true;
			}
			catch (Exception e)
			{
				MessageBox.Show(string.Format("Error: Could not build Regex from imported code.\r\nOriginal Code:{0}\r\nImported String:{1}\r\nException when building Regex:{2}", ImportTB.Text, regexStr, e));
				return false;
			}
		}


		private string convertCSToRegexStr(string csStr)
		{
			if (csStr.StartsWith("@"))
			{
				return convertCSLiteralToRegexStr(csStr);
			}

			string retVal = csStr.Substring(1);
			retVal = retVal.Substring(0, retVal.Length - 1);
			retVal = retVal.Replace("\\\"", "\"");

			return retVal;
		}

		private string convertCSLiteralToRegexStr(string csStr)
		{
			string retVal = csStr.Substring(2);
			retVal = retVal.Substring(0, retVal.Length - 1);
			retVal = retVal.Replace("\"\"", "\"");

			return retVal;
		}

	}
}
